package com.auntvt.timo.jpax.core.utils;

import com.auntvt.timo.jpax.core.interfaces.JpaxFunction;

import java.lang.invoke.SerializedLambda;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Lambda工具
 *
 * @author 小懒虫 <auntvt@163.com>
 * @date 2021/6/25
 */
public class LambdaUtil {

    /**
     * 获取方法名称
     *
     * @param fun 方法引用
     * @return 方法名
     */
    public static <T, R> String getMethodName(JpaxFunction<T, R> fun) {
        try {
            Method writeReplace = fun.getClass().getDeclaredMethod("writeReplace");
            writeReplace.setAccessible(true);
            Object invoke = writeReplace.invoke(fun);
            SerializedLambda serializedLambda = (SerializedLambda) invoke;
            return serializedLambda.getImplMethodName();
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            return null;
        }
    }

    /**
     * 获取实体类字段名称
     *
     * @param fun 实体类get方法引用
     * @return 字段名称
     */
    public static <T, R> String getFieldName(JpaxFunction<T, R> fun) {
        String methodName = getMethodName(fun);
        if (methodName == null) {
            return null;
        }
        String name = methodName.replaceFirst("get|is", "");
        return name.substring(0, 1).toLowerCase() + name.substring(1);
    }

}
